const router = require('koa-router')()
const { SucceedMess, ErrMess } = require('../res-message/index')
const { userVerify } = require('../middleware/loginCheck')
const { address, addressList, getaddress, updataAddress } = require('../controller/addressDb')

router.prefix('/api/user/address')

// 地址创建接口
router.post('/', userVerify, async (ctx, next) => {
    const userInfo = ctx.session.userInfo
    const username = userInfo.username
    const data = ctx.request.body
    console.log(data)
    try{
        const getAddress = await address(username, data)
        ctx.body = new SucceedMess(getAddress)
    }catch(e){
        console.error(e)
        ctx.body = new ErrMess(10004, '创建地址失败')
    }
})

// 获取收货地址列表
router.get('/', userVerify, async (ctx,next) => {
    const { username } = ctx.session.userInfo

    try {
        const addressListObj = await addressList(username)
        ctx.body = new SucceedMess(addressListObj)
    }catch(e){
        console.error(e)
        ctx.body = new ErrMess(10005, "获取地址列表失败");
    }

})


// 获取单个收货地址
router.get('/:id', userVerify, async (ctx, next) => {
    const id = ctx.params.id
    const address = await getaddress(id)
    
    ctx.body = new SucceedMess(address)
})

// 更新收货地址
router.post('/:id', userVerify, async (ctx, next) => {
    const { username } = ctx.session.userInfo
    const data = ctx.request.body
    const id = ctx.params.id

    try {
        const updataMess = await updataAddress(username, data, id);
        ctx.body = new SucceedMess(updataMess)
    }catch(e){
        console.error(e)
        new ErrMess(10006, "获取地址列表失败")
    }
    
})



module.exports = router
